<template>
	<view>
		<block v-if="list.length>0">
			<view class="order-list-item" v-for="item in list" :key="item.number"
				:class="item.status==2?'':'order-list-item-done'">
				<view class="order-header">
					<view class="header">
						<text class="title">{{item.serviceName}}</text>
						<view class="long-order-title" v-if="item.num>1">长期订单/{{item.num}}次</view>
					</view>
					<text class="price">￥{{item.price}}</text>
				</view>
				<view class="order-desc">
					<view class="address">
						<text class="address-detail text-overflow">{{item.address}}</text>
						<text>{{item.distance}}Km</text>
					</view>
					<text class="date" v-if="item.scheduleTime">{{formatTime(item.scheduleTime)}}</text>
					<view class="consume" v-show="item.status!=3  && item.consumableBagId">
						<image src="../../../static/img/index/start.png" mode=""></image>自备耗材
					</view>
				</view>
				<view class="order-bottom">
					<view class="">
						<image class="img" src="" mode="" :src="item.avatarJson"></image>
						<text class="user">{{item.nick}}</text>
					</view>
					<view class="order-button" :class="{'blue':item.status==2}" @click="judage(item)">
						<text v-if="!item.canGrab && item.status == 2">{{item.timeLeft+'秒后'}}</text>
						{{orderStatus(item.status)}}
					</view>
				</view>
			</view>
			<view class="divider" style="height: 8rpx;background: #F3F6F6;"></view>
		</block>
		<block v-else>
			<view class="none" :style="'height:'+noneHeight+'rpx'">
				<image src="../../../static/none/order.png" mode=""
					style="margin-top: 180rpx;width: 442rpx;height: 354rpx; margin-bottom: 80rpx;"></image>
				<view class="" style="">
					当前城市暂无订单
				</view>
			</view>
		</block>

		<uni-confirm :show="confirmShow" title=" 提示" :content="confirmContent" @cancel="bindBtn('cancel')"
			@confirm="bindBtn('confirm')">
		</uni-confirm>
	</view>
</template>

<script>
	import uniConfirm from '@/components/uni-ui/uni-confirm/uni-confirm.vue'
	import {
		selectAllUrgencyLinkman,
		getHomeDate
	} from '@/apis/security/index.js'
	import {
		getLoginInfo
	} from '@/apis/login/index.js'
	import {
		selectOrderInfo,
	} from '@/apis/order/index.js'
	export default {
		props: {
			orderList: {
				type: Array, //订单列表
				default: () => []
			},
			serverTime: {
				default: '',
			},
			vipInfo: {
				default: null
			}
		},
		watch: {
			// 监听 order 或 serverTime 变化（父组件更新时重新计算）
			orderList: {
				immediate: true,
				handler() {
					this.list = JSON.parse(JSON.stringify(this.orderList))
					console.log(this.list)
					this.list.forEach(item => {
						if (this.vipInfo) {
							item.grabTime = item.vipNurseLookDate
						} else {
							item.grabTime = item.nurseLookDate
						}
					})
					// 初始化所有订单的倒计时
					this.nowTime = this.serverTime
					this.initCountdowns();
					// this.initCountdown();
				}
			},
			serverTime: {
				immediate: true,
				handler() {
					this.nowTime = this.serverTime
					this.lastSyncTimeLeft = 0
					if(this.list.length > 0) {
						this.initCountdowns();
					}
				}
			},
			vipInfo: {
				immediate: true,
				deep: true,
				handler() {
					console.log("会员=======", this.vipInfo)
					if (this.list.length > 0) {
						this.list.forEach(item => {
							if (this.vipInfo) {
								item.grabTime = item.vipNurseLookDate
							} else {
								item.grabTime = item.nurseLookDate
							}
						})
					}
					console.log("this.list", this.list)
				}
			},
		},
		data() {
			return {
				list: [],
				visible: false,
				height: '',
				contactList: [],
				confirmShow: false,
				confirmType: 0, //未实名1 未资格认证2 未添加紧急联系人
				confirmContent: '',
				timer: null,
				lastSyncTimeLeft: 0,
				nowTime: ''
			}
		},
		onShow() {
			this.getAtte()
		},
		mounted() {

			// 每秒更新倒计时
			this.timer = setInterval(() => {

				if (this.lastSyncTimeLeft == 60) {
					this.getDate()
				}
				this.updateCountdowns();
				this.lastSyncTimeLeft += 1


			}, 1000);
		},
		destroyed() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		created() {

		},
		components: {
			uniConfirm
		},
		computed: {
			noneHeight() {
				return this.$store.state.system.windowHeight - this.$store.state.system.statusBarHeight - uni.upx2px(368) -
					uni.upx2px(88) - 44
			}
		},
		methods: {
			getDate() {
				console.log("销毁")
				getHomeDate().then(res => {
					console.log(res)
					if(res.success) {
						this.lastSyncTimeLeft == 0
						this.nowTime = res.object
						console.log("现在时间",this.nowTime)
						this.initCountdowns()
					}
				})
			},
			// 初始化所有订单的倒计时
			initCountdowns() {
				const now = new Date(this.nowTime).getTime();
				this.list.forEach(order => {
					const grabTime = new Date(order.grabTime).getTime();
					const diff = Math.floor((grabTime - now) / 1000);
					console.log("diff", order.grabTime, now)
					console.log("diff", diff)
					this.$set(order, 'timeLeft', diff > 0 ? diff : 0);
					this.$set(order, 'canGrab', order.timeLeft <= 0);
				});
			},
			// 更新所有订单的倒计时
			updateCountdowns() {
				this.list.forEach(order => {
					if (order.canGrab && order.status == 2) return;
					order.timeLeft -= 1;
					if (order.timeLeft <= 0) {
						order.timeLeft = 0;
						order.canGrab = true;
						// this.$emit('can-grab', order); // 通知父组件可抢单
					}
				});
			},

			async getAtte() {
				// if(!this.$store.state.attestStatus){
				let nurseId = this.$store.state.userInfo.id
				let res = await getLoginInfo({
					nurseId
				})
				console.log(res);
				if (res.success) {
					// this.userInfo = res.object
					// let attestStatus = res.object.attestStatus == 2 ? true : false
					// this.$store.commit('setAttestStatus', attestStatus)
					// this.$store.commit('setUserInfo', res.object)
				}
			},
			//confirm 确定取消
			async bindBtn(type) {
				console.log(type)
				if (type == 'confirm') {
					if (this.confirmType == 1) {
						uni.navigateTo({
							url: '../../../pages/iden/iden/iden?type=0'
						})
					} else if (this.confirmType == 2) {
						uni.navigateTo({
							url: '../../../pages/iden/iden/iden?type=1'
						})
					} else if (this.confirmType == 3) {
						uni.navigateTo({
							url: '../../../pages/emergency-contact/edit/edit'
						})
					}
				} else {
					console.log('quxiao')
				}
				this.confirmShow = false
			},
			async init() {
				let res = await selectAllUrgencyLinkman()
				this.contactList = res.object
				return res.object.length
			},
			async judage(item) {
				let {
					number,
					status,
					num,
					canGrab,
					grabTime
				} = item
				// 未登录-直接跳转到登录页面-产品说的……
				if (!this.$store.state.userInfo.id) {
					let res = await this.$store.dispatch('preLogin')
					console.log(res, '....................')
					if (res) {
						uni.navigateTo({
							url: '../../login-register/one-key-login/one-key-login'
						})
					} else {
						uni.navigateTo({
							url: '../../login-register/login/login'
						})
					}
					return
				}
				
				
				if(item.timeLeft < 60) {
					let res = await selectOrderInfo({
						number
					})
					if (res.success) {
						
						if(res.object.status != 2) {
							item.status = res.object.status
							return uni.showToast({
								title: '该订单已被其他护士接单',
								icon: 'none'
							})
						} else {
							this.takeOrder(item)
						}
					} 
				} else {
					this.takeOrder(item)
				}
				
			},
			// 实名认证状态：0未认证 1 2
			// 职业机构认证状态0未认证 1已认证 2审核中 3失败了

			async takeOrder(item) {
				let {
					number,
					status,
					num,
					canGrab,
					grabTime
				} = item
				

			
				if (grabTime) {
					if (!canGrab) {
						return uni.showToast({
							title: '暂不可抢',
							icon: 'none'
						})
					}
				}


				// 未实名认证
				if (!this.$store.state.nameStatus) {
					this.confirmShow = true
					this.confirmType = 1
					this.confirmContent = '应相关国家规定，为确保平台信息安全，需进行实名认证才可继续！'
					console.log('weishiming')
					// uni.showModal({
					// 	title:'提示',
					// 	content:'应相关国家规定，为确保平台信息安全，需进行实名认证才可继续！',
					// 	cancelText:'稍后认证',
					// 	confirmText:'立即认证',
					// 	confirmColor:'#3C8EFF',
					// 	success: (res) => {
					// 		if(res.confirm){
					// 			uni.navigateTo({
					// 				url:'../../../pages/iden/iden/iden?type=0'
					// 			})
					// 		}
					// 	}
					// })
					return
				}

				// 未职业资格认证
				if (!this.$store.state.attestStatus) {
					this.confirmShow = true
					this.confirmType = 2
					this.confirmContent = '应相关国家规定，为确保平台信息安全，需通过执业资格认证才可继续！'
					// uni.showModal({
					// 	title:'提示',
					// 	content:'应相关国家规定，为确保平台信息安全，需通过执业资格认证才可继续！',
					// 	cancelText:'稍后认证',
					// 	confirmText:'立即认证',
					// 	confirmColor:'#3C8EFF',
					// 	success: (res) => {
					// 		if(res.confirm){
					// 			uni.navigateTo({
					// 				url:'../../../pages/iden/iden/iden?type=1'
					// 			})
					// 		}
					// 	}
					// })
					return
				}
				let res12 = await selectAllUrgencyLinkman()

				if (!res12.object || res12.object.length == 0) {
					this.confirmShow = true
					this.confirmType = 3
					this.confirmContent = '请先添加紧急联系人'
					// uni.showModal({
					// 	title:'提示',
					// 	content:'请先添加紧急联系人',
					// 	confirmColor:'#3C8EFF',
					// 	success: (res) => {
					// 		if(res.confirm){
					// 			uni.navigateTo({
					// 				url:'../../../pages/emergency-contact/edit/edit'
					// 			})
					// 		}
					// 	}
					// })
					return
				}
				// 去接单了,和订单详情共用一个页面
				if (status == 2) {
					uni.navigateTo({
						url: '../../../pages/order/order-detaile/order-detaile?number=' + number + '&status=' +
							status
					})
				} else {
					// #ifdef APP-PLUS
					plus.nativeUI.toast('该订单已被接单！')
					// #endif
					// #ifndef APP-PLUS
					uni.showToast({
						icon: 'none',
						title: '该订单已被接单！'
					})
					// #endif
					return ''
				}
			},
			closeModal() {
				this.visible = false;
			},
			goCertificate() {
				console.log('1')
				this.visible = false;
			},
			// 日期转换
			formatTime(time) {
				let date = new Date(time)
				let res = time.split(' ')
				let a = res[0].split('/')
				let b = a[0] + '.' + a[1] + '.' + a[2]
				res[0] = b + this.formatDate(date.getDay())
				res[1] = this.dayTime(date) + res[1].slice(0, 5)
				return res[0] + ' | ' + res[1]
			},
			formatDate(time) {
				let title = ''
				switch (time) {
					case 1:
						title = '周一';
						break;
					case 2:
						title = '周二';
						break;
					case 3:
						title = '周三';
						break;
					case 4:
						title = '周四';
						break;
					case 5:
						title = '周五'; //服务中
						break;
					case 6:
						title = '周六'; //退款中
						break;
					case 0:
						title = '周日';
						break;
				}
				return title
			},
			orderStatus(status) {
				let title = ''
				switch (status) {
					case 2:
						title = '抢单';
						break;
					case 3:
						title = '已抢单';
						break;
					default:
						title = "已抢单"
						break;

				}
				return title
			},
			dayTime(date) {
				let hoursTip = ''
				if (date.getHours() >= 0 && date.getHours() < 12) {
					hoursTip = "上午"
				} else if (date.getHours() >= 12 && date.getHours() < 18) {
					hoursTip = "下午"
				} else {
					hoursTip = "晚上"
				}
				return hoursTip
			}
		}
	}
</script>

<style lang="less" scoped>
	@muted-color: rgba(0, 0, 0, 0.1); //置灰颜色

	// 订单
	.order-list-item {
		padding: 30rpx 26rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		margin-top: 16rpx;

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.header {
				display: flex;

				.title {
					font-size: 36rpx;
					font-weight: 500;
					color: #333333;
				}

				.long-order-title {
					// padding: 8rpx 16rpx; 
					font-size: 24rpx;
					font-weight: 500;
					line-height: 46rpx;
					text-align: center;
					width: 176rpx;
					height: 46rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					background: linear-gradient(90deg, #7093FA 0%, #8BB0F9 100%);
					border-radius: 26px 26px 26px 0rpx;
					color: #ffffff;
					margin-left: 16rpx;
					// // background: linear-gradient(to right, #00CF6E 0%, #3C8EFF 100%);
					// background: url('~@/static/img/index/long_order_bg.png');
					// background-size: 100% 100%;
				}
			}

			.price {
				font-size: 36rpx;
				font-weight: 500;
				color: #FF4F4F;

			}
		}

		.order-desc {
			font-size: 28rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #666666;

			.address {
				display: flex;
				justify-content: space-between;
				margin: 16rpx 0rpx;

				.address-detail {
					width: 532rpx;
				}
			}

			.date {
				padding-right: 24rpx;
			}

			.consume {
				font-size: 28rpx;
				color: #666666;
				float: right;
				display: flex;
				align-items: center;

				image {
					width: 34rpx;
					height: 34rpx;
					margin-right: 8rpx;
				}
			}
		}

		.order-bottom {
			display: flex;
			justify-content: space-between;
			margin-top: 16rpx;

			.img {
				width: 56rpx;
				height: 56rpx;
				background-color: #fafafb;
				vertical-align: middle;
				margin-right: 16rpx;
				border-radius: 50%;
			}

			.user {
				font-size: 24rpx;
				font-weight: 400;
				color: #999999;
			}

			.order-button {
				width: 216rpx;
				height: 56rpx;
				text-align: center;
				line-height: 56rpx;
				font-size: 28rpx;
				font-weight: 500;
				color: #ffffff;
				border-radius: 16rpx;

				&.blue {
					background: #3C8EFF !important;
				}
			}
		}
	}

	// 已接单样式
	.order-list-item.order-list-item-done {
		.order-header {
			.title {
				color: rgba(0, 0, 0, 0.38);
			}

			.long-order-title {
				// color: rgba(255, 255, 255, 0.38);
				color: #FFFFFF;
				background: #E8E8E8;
				// background: url('~@/static/img/index/long_order_disbg.png') !important;
			}

			.price {
				color: @muted-color;
			}
		}

		.order-desc {
			color: @muted-color;

			.address-detail {
				width: 532rpx;
			}
		}

		.consume {
			color: @muted-color;
		}

		.order-bottom {
			.img {
				background: rgba(255, 255, 255, 0.6);
			}

			.user {
				color: @muted-color;
			}

			.order-button {
				color: #ffffff;
				background: @muted-color;
			}
		}
	}

	.none {
		// height: 100vh;
		font-size: 36rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		text-align: center;

		image {
			display: block;
			margin: 0 auto;

		}

	}

	// 资格认证
	// 资格认证
	.modal {
		width: 100%;
		height: 100vh;
		position: fixed;
		top: 0;
		bottom: 0;
		z-index: 12;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		display: flex;
		justify-content: center;
		align-items: center;
		background: rgba(0, 0, 0, 0.1);

		.modal-content {
			width: 540rpx;
			font-size: 32rpx;
			color: #333333;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			background-color: #ffffff;
			box-shadow: 0rpx 12rpx 16rpx -8rpx rgba(0, 0, 0, 0.05), 0rpx 10rpx 46rpx 8rpx rgba(0, 0, 0, 0.05), 0rpx 24rpx 38rpx 4rpx rgba(0, 0, 0, 0.05);
			border-radius: 12rpx;

			.title {
				padding: 42rpx 30rpx;
				border-bottom: solid 1rpx #e5e5e5;
			}

			.btn {
				display: flex;
				font-size: 32rpx;
				color: #3C8EFF;
				padding: 24rpx 0;
				border-radius: 12rpx;

			}
		}
	}
</style>